const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const favicon = require('serve-favicon');
const logger = require('morgan');
const _= require('lodash');

const config = require('./env/context.config');
const db = require('./env/mongodb.config');
const resourceUtil = require('../app/utils/resourceUtil');

//connect mongodb with goose
mongoose.Promise = global.Promise;
if(db.mongodb.debug){
    mongoose.set('debug',true);
}
mongoose.connect(db.mongodb.uri,db.mongodb.options,function(err){
    if(err){
        console.error('Connect to DB failed')
        console.error(err);
        process.exit(-1);
    }else {
        console.log('info: Connecred to DB success:'+db.mongodb.uri+" "+db.mongodb.options);
    }
});

//web server config
var app = require('./env/app.config');
var router = express.Router();



//view engine
app.set('views',path.join(__dirname,'views'));
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');



//register middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser('love'));
app.use(session({
    resave: true, // don't save session if unmodified
    saveUninitialized: false, // don't create session until something stored
    secret: 'love'
    // ,cookie:{maxAge:10*60*1000}
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//access static resource
app.use(express.static(path.join(__dirname,'../../public')));

//set header

app.use('*',(req,res,next)=>{
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Powered-By,Content-Type");
    // if(req.originalUrl.indexOf("/O2OCustomer/api/orders")>-1||req.originalUrl.indexOf("/O2OCustomer/api/comments")>-1){
    //     if(_.isEmpty(req.session.customerInfo)){
    //         res.json({result:false,errMsg:'Not login'});
    //     }
    // }
    next();
});





//load routes
resourceUtil.getGlobbedFiles('./src/app/routes/**/*.js').forEach(function(routePath) {
    require(path.resolve(routePath))(router);
});
// var userRouter = require('../app/routes/user.route')(router);
app.use(config.server.context,router);

app.set('port',config.server.port);

module.exports = app;





